package io.netty.study.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * @author YueGod
 * @since 2024/4/19
 */
public class NettyClientStart {

    private final String host;
    private final int port;

    public NettyClientStart(String host, int port) {
        this.host = host;
        this.port = port;
    }


    public void start() throws Exception {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringDecoder());
                            ch.pipeline().addLast(new StringEncoder());
                            ch.pipeline().addLast(new EchoClientHandler());
                        }
                    });

            // 连接到服务端
            ChannelFuture f = b.connect(host, port).sync();

            // 等待连接被关闭
            f.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws Exception {
        new NettyClientStart("localhost", 8080).start();
    }
}

class EchoClientHandler extends io.netty.channel.SimpleChannelInboundHandler<String> {
    @Override
    public void channelActive(io.netty.channel.ChannelHandlerContext ctx) {
        ctx.writeAndFlush("Hello from " + NettyClientStart.class.getSimpleName()); // 发送消息到服务端
    }

    @Override
    protected void channelRead0(io.netty.channel.ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("Server replied: " + msg); // 打印服务端返回的信息
    }

    @Override
    public void exceptionCaught(io.netty.channel.ChannelHandlerContext ctx, Throwable cause) {
        cause.printStackTrace();
        ctx.close();
    }
}